package com.cssl.util;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.cssl.domain.dto.PaymentParam;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.alipay.api.AlipayConstants.APP_ID;
import static com.alipay.api.AlipayConstants.CHARSET;

public class AlipayPayment {

    private String APPID;
    private String APP_PRIVATE_KEY;
    private String CHAR_SET;
    private String ALIPAY_PUBLIC_KEY;
    private String GATEWAY_URL;
    private String FORMAT;
    private String SIGN_TYPE;
    private String NOTIFY_URL;
    private String returnUrl;


    public AlipayPayment() {
    }


    public AlipayPayment(String APPID, String APP_PRIVATE_KEY, String CHAR_SET, String ALIPAY_PUBLIC_KEY, String GATEWAY_URL, String FORMAT, String SIGN_TYPE, String NOTIFY_URL, String returnUrl) {
        this.APPID = APPID;
        this.APP_PRIVATE_KEY = APP_PRIVATE_KEY;
        this.CHAR_SET = CHAR_SET;
        this.ALIPAY_PUBLIC_KEY = ALIPAY_PUBLIC_KEY;
        this.GATEWAY_URL = GATEWAY_URL;
        this.FORMAT = FORMAT;
        this.SIGN_TYPE = SIGN_TYPE;
        this.NOTIFY_URL = NOTIFY_URL;
        this.returnUrl = returnUrl;
    }

    public Result payZFB(PaymentParam paymentParam) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APPID, APP_PRIVATE_KEY, FORMAT, CHAR_SET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);

        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();

        /** 设置业务参数  **/
        AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();

        /** 商户订单号，商户自定义，需保证在商户端不重复，如：20200612000001 **/
        model.setOutTradeNo(paymentParam.getOutTradeNo());

        List<String> collect = Arrays.stream(paymentParam.getSubject()).collect(Collectors.toList());
        String result = String.join(",", collect);
        String subject="";
        try {
            subject =  new String(result.getBytes(),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        /**订单标题 **/
        model.setSubject(subject);

        /** 订单金额，精确到小数点后两位 **/
        model.setTotalAmount(paymentParam.getTotalAmount()+"");

        /** 订单描述 **/
        model.setBody("商品购买");

        /** 将业务参数传至request中 **/
        request.setBizModel(model);

        /** 异步通知地址，以http或者https开头的，商户外网可以post访问的异步地址，用于接收支付宝返回的支付结果，如果未收到该通知可参考该文档进行确认：			https://opensupport.alipay.com/support/helpcenter/193/201602475759 **/
        request.setNotifyUrl("https://127.0.0.1/users/test");
        /******可选参数******/

        AlipayTradePrecreateResponse response = null;
        try {
            /** 通过alipayClient调用API，获得对应的response类  **/
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {

            e.printStackTrace();
        }

        /** 获取接口调用结果，如果调用失败，可根据返回错误信息到该文档寻找排查方案：https://opensupport.alipay.com/support/helpcenter/101 **/
        System.out.println(response.getBody());
        return Result.result(InfoCode.OK, InfoCode.MESSAGE_OK, response.getBody(), System.currentTimeMillis());
    }

    /**
     * 退款
     *
     * @param bizPayNo
     * @param money
     * @return
     */
    public Result refund(String bizPayNo, Float money) {
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL,
                APP_ID,
                APP_PRIVATE_KEY,
                FORMAT,
                CHARSET,
                ALIPAY_PUBLIC_KEY,
                SIGN_TYPE);
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        // 根据bizPayNo查订单金额 这是我自己的业务代码
        //LambdaQueryWrapper<Pay> wrapper = Wrappers.lambdaQuery();
        //wrapper.eq(Pay::getBizPayNo,bizPayNo);
        //Pay pay = getOne(wrapper);
        // bizPayNo订单号  money 价格
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", bizPayNo);
        bizContent.put("refund_amount", money);
        bizContent.put("out_request_no", "HZ01RF001");
        bizContent.put("body", money != null ? "支付超时" : "订单取消");

//        // 返回参数选项，按需传入
//        JSONArray queryOptions = new JSONArray();
//        queryOptions.add("refund_detail_item_list");
//        bizContent.put("query_options", queryOptions);

        request.setBizContent(bizContent.toString());
        try {
            AlipayTradeRefundResponse response = alipayClient.execute(request);
            if (response.isSuccess()) {
                System.out.println("退款成功");
                return Result.result(InfoCode.OK, InfoCode.MESSAGE_OK, true, System.currentTimeMillis());
            } else {
                System.out.println("退款失败");
                return Result.result(InfoCode.FAILED, InfoCode.MESSAGE_FAILED, false, System.currentTimeMillis());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(InfoCode.FAILED, InfoCode.MESSAGE_FAILED, System.currentTimeMillis());
        }
    }

    public String getAPPID() {
        return APPID;
    }

    public void setAPPID(String APPID) {
        this.APPID = APPID;
    }

    public String getAPP_PRIVATE_KEY() {
        return APP_PRIVATE_KEY;
    }

    public void setAPP_PRIVATE_KEY(String APP_PRIVATE_KEY) {
        this.APP_PRIVATE_KEY = APP_PRIVATE_KEY;
    }

    public String getCHAR_SET() {
        return CHAR_SET;
    }

    public void setCHAR_SET(String CHAR_SET) {
        this.CHAR_SET = CHAR_SET;
    }

    public String getALIPAY_PUBLIC_KEY() {
        return ALIPAY_PUBLIC_KEY;
    }

    public void setALIPAY_PUBLIC_KEY(String ALIPAY_PUBLIC_KEY) {
        this.ALIPAY_PUBLIC_KEY = ALIPAY_PUBLIC_KEY;
    }

    public String getGATEWAY_URL() {
        return GATEWAY_URL;
    }

    public void setGATEWAY_URL(String GATEWAY_URL) {
        this.GATEWAY_URL = GATEWAY_URL;
    }

    public String getFORMAT() {
        return FORMAT;
    }

    public void setFORMAT(String FORMAT) {
        this.FORMAT = FORMAT;
    }

    public String getSIGN_TYPE() {
        return SIGN_TYPE;
    }

    public void setSIGN_TYPE(String SIGN_TYPE) {
        this.SIGN_TYPE = SIGN_TYPE;
    }

    public String getNOTIFY_URL() {
        return NOTIFY_URL;
    }

    public void setNOTIFY_URL(String NOTIFY_URL) {
        this.NOTIFY_URL = NOTIFY_URL;
    }

    public String getReturnUrl() {
        return returnUrl;
    }

    public void setReturnUrl(String returnUrl) {
        this.returnUrl = returnUrl;
    }
}
